import { IBreadcrumbType } from '@/base-ui/breadcrumb'
import { RouteRecordRaw } from 'vue-router' // 路由对象类型
let firstMenu: any = null
export function mapMenusToRoutes(userMenus: any[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []
  // 1.先去加载默认所有的routes
  const allRoutes: RouteRecordRaw[] = []
  // webpack方法=>查找指定文件夹下文件 第二个参数是否递归查找
  const routeFiles = require.context('../router/main', true, /\.ts/)
  // routeFiles.keys() 获取文件夹/文件路径数组
  routeFiles.keys().forEach((key) => {
    // 拼接路径
    const route = require('../router/main' + key.split('.')[1])
    // 把拼接的路径添加到数组中
    allRoutes.push(route.default)
  })
  // 2.根据菜单获取需要添加的routes
  const _recurseGetRoute = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 2) {
        const route = allRoutes.find((route) => route.path === menu.url)
        if (route) routes.push(route)
        // 拿到菜单里第一个对象用于刷新页面后重定向
        if (!firstMenu) {
          firstMenu = menu
        }
      } else {
        _recurseGetRoute(menu.children)
      }
    }
  }
  // 递归函数 查找所有routes中的path与当前传入菜单的url相匹配的项 存入数组中
  _recurseGetRoute(userMenus)
  return routes
}

// 在全部routes中找到当前url的路由对象
export function pathMapToMenu(userMenus: any, currentPath: string, breadcrumbs?: IBreadcrumbType[]): any {
  for (const menu of userMenus) {
    if (menu.type === 1) {
      const findMenu = pathMapToMenu(menu.children ?? [], currentPath)
      if (findMenu) {
        breadcrumbs?.push({ name: menu.name })
        breadcrumbs?.push({ name: findMenu.name })
        return findMenu
      }
    } else if (menu.type === 2 && menu.url === currentPath) {
      return menu
    }
  }
}

export function pathMapBreadcrumbs(userMenus: any, currentPath: string): any {
  const breadcrumbs: IBreadcrumbType[] = []
  pathMapToMenu(userMenus, currentPath, breadcrumbs)
  return breadcrumbs
}

export function mapMenusToPermissions(userMenus: any[]) {
  const permissions: string[] = []
  const _recurseGetPermission = (menus: any) => {
    for (const menu of menus) {
      if (menu.type === 1 || menu.type === 2) {
        _recurseGetPermission(menu.children ?? [])
      } else if (menu.type === 3) {
        permissions.push(menu.permission)
      }
    }
  }
  _recurseGetPermission(userMenus)
  return permissions
}

export function mapMenuLeafKeys(menuList: any[]) {
  const leafKeys: number[] = []
  const _recurseGetLeaf = (menuList: any[]) => {
    for (const menu of menuList) {
      if (menu.children) {
        _recurseGetLeaf(menu.children)
      } else {
        leafKeys.push(menu.id)
      }
    }
  }
  _recurseGetLeaf(menuList)
  return leafKeys
}
export { firstMenu }
